'use strict';

var mask;
var share_mask;
var discount_mask;

var detail = new Vue({
	el: '.body',
	data: {
		goods_tag_show: false, //商品标签是否显示
		goods_tag_list: [], //商品标签 如 团购，优享特惠 等
		confirm_goods_is_show: false,
		goods_num: 1,
		is_collect: false,
		collect_icon: '../images/ptsp/icon_05.png',
		is_buy_car: false, //是否添加购物车
		buy_car_icon: '../images/ptsp/icon_07.png',
		to_say_height: '',
		to_info_height: '',
		share_box_is_show: false,
		discount_box_is_show:false,  //优惠券列表框是否显示
		discount_data_list:'',//优惠券列表
		wareInfoGroup: {}, // 商品信息
		commentGroup: {}, // 商品评论
		user: {}, // 用户
		collectStatus: false, // 收藏状态
		currentSpecification: null,
		currentSpecificationIndex: -1,
		confirmType: 0,
		groupBuying: false,
		cartId: 0,
		group_sale_price:"0.00",//当前拼团选中的规格价钱
		now_sale_price: '0.00', //当前选中的规格价钱
		plus_ready:false,//plus 对象 是否准备就绪
		goods_pt_buy_bg:'linear-gradient(to right, #77d3fd, #77b6fd)',//普通商品购买按钮背景色
		buy_goods_way:"",//car group goods
	

	},
	methods: {
		//打开选择规格窗口
		show_sel_box: function show_sel_box(_ref) {
			
			var type = _ref.type,
				groupBuying = _ref.groupBuying;
			var way = _ref.way;
			console.log(way) // 0-->购物车  1-->立即购买  2-->拼团
		 	if(way==0){
		 		this.buy_goods_way = "car"
		 	}else if(way==1){
		 		this.buy_goods_way = "goods"
		 	}else if(way==2){
		 		this.buy_goods_way = "group"
		 	}
			this.confirmType = type;
			this.groupBuying = groupBuying;
			if(this.confirmType == 0 && this.is_buy_car) {
				this.deleteCartById();
				return false;
			}
			this.confirm_goods_is_show = true;
			mask.show();
		},
		//关闭选择规格窗口
		close_sel_box: function close_sel_box() {
			mask.close();
			this.confirm_goods_is_show = false;
		},
		//打开优惠券列表框
		open_discount_box:function(){
			
			if(this.discount_data_list == 0 ){
				mui.toast("暂无优惠券");
				return
			}
			discount_mask.show();
			this.discount_box_is_show = true;
		},
		//减少数量
		cut_num: function cut_num() {
			if(this.goods_num >= 2) {
				this.goods_num--;
			}
		},
		//增加数量
		add_num: function add_num() {
			if(this.wareInfoGroup.stock > this.goods_num) {
				this.goods_num++;
			}
		},
		// 领取优惠券
		get_this_discount:function(k){
			if(this.discount_data_list[k].geted){
				mui.toast("您已领取过");
				// 关闭优惠券领取窗口
				discount_mask.close();
				this.discount_box_is_show = false;
				return
			}
			var that = this;
			var disid  = this.discount_data_list[k].disid;// 优惠券ID
			// 发起 领取优惠券 请求
			$.ajax({
				type:'get',
				url:'https://zhapp.4hl.cn/app/Coupon/getcoupon',
				data:{
					uid:this.user.uid,
					youtype:2,//1-->小程序  2-->APP
					disid:disid,
				},
				success:function(res){
					
					res = JSON.parse(res);
					 
					if(res.code==1){
						 
						mui.toast("领取成功")
						// 关闭优惠券领取窗口
						discount_mask.close();
						this.discount_box_is_show = false;
						
						// 刷新优惠券数据
						up_data_discount(that.user.uid)
					}
				},
				error:function(err){
					alert(JSON.stringify(err))
				}
			})
			 
		},
		//联系客服
		call_kefu: function call_kefu() {
			mui.toast("联系客服");
		},
		//收藏
		collect: function collect() {
			var _this = this;
			var goodsid = this.wareInfoGroup.goodsid;
			var uid = this.user.uid;
			//  status(0 => 未收藏 1 => 收藏) type (0 商城)

			if(_this.collectStatus == 0) {
				$.get(url + 'api/collect/addcollect', {
					goodsid: goodsid,
					uid: uid,
					status: 0,
					type: 0
				}, function(response) {
					var responseData = JSON.parse(response);
					// 返回结果 code 为  1  则 收藏 成功
					if(responseData.code == '1') {
						var msg = responseData.msg;
						mui.toast(msg);
						_this.collectStatus = true;
						_this.collect_icon = '../images/ptsp/icon2_05.png';
					}
				});
			} else {

				$.get(url + 'api/collect/addcollect', {
					goodsid: goodsid,
					uid: uid,
					status: 1,
					type: 0
				}, function(response) {
					var responseData = JSON.parse(response);
					// 返回结果 code 为  1  则 取消  收藏 成功
					if(responseData.code == '1') {
						var msg = responseData.msg;
						mui.toast(msg);
						_this.collectStatus = false;
						_this.collect_icon = '../images/ptsp/icon_05.png';
					}
				});
			}
		},
		//规格
		specificationActive: function specificationActive(index) {
			// 选择当前规格
			this.currentSpecification = this.wareInfoGroup.specification[index];
			this.currentSpecificationIndex = index;
			this.now_sale_price = this.wareInfoGroup.specification[index].price;
			this.group_sale_price = this.wareInfoGroup.specification[index].spell_money;
			
		},
		//滚动至评论
		to_say: function to_say(e) {
			console.log('to_say');
			var that = this;
			document.querySelector(".ptsp_active").className = "";
			e.target.className = 'ptsp_active';
			mui('.mui-scroll-wrapper').scroll().scrollTo(0, -that.to_say_height, 500);
		},
		//滚动至商品详情
		to_detail: function to_detail(e) {
			document.querySelector(".ptsp_active").className = "";
			console.log('to_detail');
			e.target.className = 'ptsp_active';

			var that = this;
			// var pingjia_height = document.getElementById("pingjia").clientHeight;
			// var height = pingjia_height + 579;
			mui('.mui-scroll-wrapper').scroll().scrollTo(0, -that.to_info_height, 500);
		},
		//滚动到商品顶部
		to_goods: function to_goods(e) {

			console.log('to_goods');
			document.querySelector(".ptsp_active").className = "";

			e.target.className = 'ptsp_active';

			mui('.mui-scroll-wrapper').scroll().scrollTo(0, 0, 500);
		},
		//删除购物车
		deleteCartById: function deleteCartById() {
			var _this = this;
			$.get(url + 'api/cart/delete', {
				cartid: _this.cartId
			}, function(response) {
				var responseData = JSON.parse(response);
				if(responseData.code == '1') {
					_this.buy_car_icon = '../images/ptsp/icon_07.png';
					_this.is_buy_car = false;
					mui.toast('已从购物车删除');
				}
			});
		},
		//提交订单
		go_confirm_oreder: function go_confirm_oreder() {
			var _this = this;
			var confirmType = this.confirmType;
			if(!this.user){
				mui.toast("请先登录后再下单..")
				return
			};
			
			if(confirmType == 0) {

				// 添加购物车

				if(!_this.is_buy_car) {
					// 添加至购物车
					var currentSpecification = this.currentSpecification;
					if(!currentSpecification) {
						mui.toast("请选择商品规格");
						return false;
					}
					var rule = currentSpecification.rule;
					var goodsid = currentSpecification.goodsid;
					var num = this.goods_num;
					var uid = this.user.uid;
					$.post(url + 'app/cart/cartadd', {
						goodsid: goodsid,
						num: num,
						rule: rule,
						uid: uid
					}, function(response) {
						var responseData = JSON.parse(response);
						if(responseData.code == '1') {
							var cartId = responseData.data;
							_this.cartId = cartId;
							_this.buy_car_icon = '../images/ptsp/icon2_07.png';
							mui.toast('已添加至购物车');
							_this.is_buy_car = true;
						}
					});
				}
				this.close_sel_box();
			} else if(confirmType == 1) {
				// 直接下单
				var _currentSpecification = this.currentSpecification;
				if(!_currentSpecification) {
					mui.toast("请选择商品规格");
					return false;
				}
				var cartInfo = {
					rule: _currentSpecification.rule,
					goodsid: _currentSpecification.goodsid,
					num: this.goods_num,
					uid: this.user.uid,
					groupBuying: this.groupBuying,
					attrid: _currentSpecification.attrid,
					spell: 1,
					spell_id: 0
				};
				host_config.localStorage.setItem(host_config.cartInfo, JSON.stringify(cartInfo));
				mui.openWindow('confirm_order.html?confirmType=1&way='+this.buy_goods_way+'&sid='+this.sid);
			}
		},
		//已有拼团列表 去拼团
		publishOrder: function publishOrder(_ref2) {
			console.log(123)
			console.log(_ref2)
		 
			var _this = this;
			if(!this.user){
				mui.toast("请先登录后再参团")
				return
			};
			var id = _ref2.id,
				attrid = _ref2.attrid,
				num = _ref2.num;
			// 拼团
			var cartInfo = {
				rule: '',
				goodsid: this.wareInfoGroup.goodsid,
				num: num,
				uid: this.user.uid,
				groupBuying: true,
				attrid: attrid,
				spell: 0,
				spell_id: id
			};
			host_config.localStorage.setItem(host_config.cartInfo, JSON.stringify(cartInfo));
			util.log('confirm_order.html?confirmType=1&sid='+_this.sid)
			mui.openWindow('confirm_order.html?confirmType=1&sid='+_this.sid+"&way=group");
		},
		//打开分享
		open_share: function open_share() {
			this.share_box_is_show = true;
			share_mask.show();
			
		},
		//分享方法
		share_fun:function(n){
			/*
			 * n 为分享类型
			 * 		1	-->	分享好友
			 * 		2	-->	分享朋友圈
			 * 		3	-->	分享QQ
			 * 		4	-->	复制链接
			 * 
			 * 
			 * */
			 var that = this;
			if(!this.plus_ready){
				mui.toast("plus未准备就绪");
				return;
			}
			switch(n) {
				case 1:
					 
					share.get_share(function(share_list){ 
 						util.log(JSON.stringify(share_list))
 
						var msg = share_config ;
						 
				
						
						msg.href = msg.href + "?type=share_goods&id="+that.wareInfoGroup.goodsid
						util.log("分享信息-->> "+JSON.stringify(msg))
				
				 

						msg.extra.scene='WXSceneSession'
						 shareAction(share_list.weixin,msg)
					})
					
					break;
				case 2:
					share.get_share(function(share_list){ 
						var msg = share_config ;
						msg.href = msg.href + "?type=share_goods&id="+that.wareInfoGroup.goodsid
						util.log("分享信息-->> "+JSON.stringify(msg))
						
						msg.extra.scene='WXSceneTimeline'
						 shareAction(share_list.weixin,msg)
					}) 
					break;
				case 3:
					alert('分享QQ 开发中')
					break;
				case 4:
					alert('复制链接 开发中')
					break;
				default:
					break;
			}
		}
	},
	created: function() {
		var that = this;
		user = localStorage.getItem("user")
		this.user = user ? JSON.parse(user) : '';

		//获取 商品信息，收藏，评论等信息
		get_data(util.GetQueryString('goodsid'), this.user)
		if(util.GetQueryString('sid')){
			this.sid = util.GetQueryString('sid');	
		}
		
		document.addEventListener("plusready",function(){
			that.plus_ready = true;
		})
	},
	mounted: function mounted() {

		// 初始化蒙版遮罩
		mask_init(this)
		// 初始化滚动条
		scroll_init()
		//初始化轮播
		slider_init();
		
		setTimeout(function(){
			previewimage_init()
		},500)
		
		//mui初始化
		mui_init();
	 
		
	}
});
//分享操作
function shareAction(s,msg) {
	if ( !s ) {
		return;
	}
	if ( s.authenticated ) {
		shareMessage( s,msg );
	} else {
		s.authorize( shareMessage, function(e){
			alert( "未进行认证" );
		});
	}
}
//发送分享消息
function shareMessage(s,msg){
	s.send( msg, function(){
		mui.toast( "分享成功！" );
	}, function(e){
		alert( "分享失败："+e.message );
	} );
}
//商品标签初始化
function goods_tag_init(goods_info) {
	/*
	商品信息中
		special_offer  -->  社区精品
		recom   -->  优享特卖
		
	*/
	if(goods_info.special_offer == 1 || goods_info.recom == 1||goods_info.spell == 1) {
		
		detail.goods_tag_show = true;
		
		var goods_tag_list = [];
		if(goods_info.spell == 1) {
			goods_tag_list.push({
				tag_name: '拼团价' 
			})
		}
		if(goods_info.special_offer == 1) {
			goods_tag_list.push({
				tag_name: '社区精品'
			})
		};
		if(goods_info.recom == 1) {
			goods_tag_list.push({
				tag_name: '优享特卖'
			})
		}
		
		detail.goods_tag_list = goods_tag_list;
	} 
		
		if(!goods_info.spell){
			console.log("普通商品")
			detail.goods_pt_buy_bg = "linear-gradient(to right, #1cb3fc, #1c83fc)";
			 
		}
	 

}
//mui初始化
function mui_init() {
	mui.init({
		swipeBack: true //启用右滑关闭功能
	});
}
// 初始化蒙版遮罩
function mask_init(that) {
	mask = mui.createMask(function() {
		that.confirm_goods_is_show = false;
	});
	share_mask = mui.createMask(function() {
		that.share_box_is_show = false;
	});
	discount_mask = mui.createMask(function() {
		that.discount_box_is_show = false;
	});
	
}
// 初始化滚动条
function scroll_init() {
	mui('.mui-scroll-wrapper').scroll({
		deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
	});
}
//获取 商品信息，收藏，评论 优惠券 等信息 
function get_data(goodsId, user) { //获取 商品信息，收藏，评论等信息
	util.log("获取 商品信息，收藏，评论 优惠券 等信息 ")
	util.log("user-->"+JSON.stringify(user))
	
	var sid = util.GetQueryString("sid")
	// 获取商品信息
	// alert("开始获取商品信息:API-->'app/goods/detail'  参数:goodsid-->"+goodsId+"&sid-->"+sid)
	$.get(url + 'app/goods/detail', {
		goodsid: goodsId,
		sid:sid
	}, function(response) {
		var responseData = JSON.parse(response);
		if(responseData.code == '1') {
			var wareItem = responseData.data;
			console.log(responseData);
			detail.wareInfoGroup = wareItem;
			detail.wareInfoGroup.firstPic = wareItem.pics[0];
			detail.wareInfoGroup.lastPic = wareItem.pics[wareItem.pics.length - 1];
			detail.now_sale_price = detail.wareInfoGroup.min_price;
			
			goods_tag_init(responseData.data);
			console.log("------+++----")
			console.log(detail.wareInfoGroup)
		}

		setTimeout(function() {
			height_init(); //初始化顶部切换滚动距离
			init_banner_num(); //初始化轮播数字
		}, 500);
		if(window.plus) {
			plus.nativeUI.closeWaiting();
		}
	});

	// 获取评论
	$.get(url + 'api/comment/commentLists', {
		goodsid: goodsId,
		type:1
	}, function(response) {
		var responseData = JSON.parse(response);
		if(responseData.code == '1') {
			var data = responseData.data;
			for(var dataItem in data) {
				
				data[dataItem].createtime = util.date_format(data[dataItem].createtime*1000)
//				var localeDate = new Date(data[dataItem].createtime).toLocaleDateString();
//				data[dataItem].createtime = localeDate.replace('//', '-');
			}
			console.log("---------")
			console.log(data)
// 			for(var i = 0;i<data.length;i++){
// 				var arr = data[i].pics[0].split(",");
// 				arr.splice(arr.length-1,1)
// 				data[i].pics = arr;
// 			}
	 
			
 
			detail.commentGroup = data;
			
		}
	});

	var uid = user.uid;

	// 获取默认收藏状态
	$.get(url + 'api/collect/iscollect', {
		goodsid: goodsId,
		uid: uid
	}, function(response) {
		var responseData = JSON.parse(response);
//		console.log(response)
		if(responseData.code == '1') {
			detail.collectStatus = true;
			detail.collect_icon = '../images/ptsp/icon2_05.png';
		} else {
			detail.collectStatus = false;
			detail.collect_icon = '../images/ptsp/icon_05.png';
		}
	});
	// 获取 对应社区的 优惠券列表
	up_data_discount(user.uid)
}

// 获取 对应社区的 优惠券列表
function up_data_discount(uid){
	var sq_info = JSON.parse(localStorage.getItem("address"));
	util.log("社区信息-->"+JSON.stringify(sq_info))
	$.ajax({
		type:"get",
		url:"https://zhapp.4hl.cn/app/coupon/couponApp",
		data:{
			uid:uid,
			bid:sq_info.sqid,
			youtype:2
		},
		success:function(res){
		
			res = JSON.parse(res);
			util.log("优惠券信息-->"+JSON.stringify(res));

			// 判断是否已领取
			
 
			for(var i =0;i<res.length;i++){
				if(res[i].num>0){
					console.log("已领取")
					res[i].geted = true;
				}
			}
 
			detail.discount_data_list = res;
			
			
		},
		error:function(err){
			alert("服务器错误")
		}
	});
}
//初始化 滑动高度
function height_init() { //初始化 滑动高度
	var that = detail;

	var banner_height = document.querySelector("#shangpin").clientHeight;
	var goods_info_height = document.querySelector("#goods_info").clientHeight;

	if(detail.wareInfoGroup.spell == 1) {
		var ptsp_users_height = document.querySelector(".ptsp_users").clientHeight;
		//      console.log('ptsp_users_height->' + ptsp_users_height);
	}

	var hr_20_height = document.querySelector(".hr_20").clientHeight;
	var say_height = document.querySelector("#pingjia").clientHeight;
	//  console.log('banner_height->' + banner_height);
	//  console.log('goods_info_height->' + goods_info_height);
	//
	//  console.log('hr_20_height->' + hr_20_height);
	//  console.log('say_height->' + say_height);
	if(detail.wareInfoGroup.spell == 1) {
		var ptsp_users_height = document.querySelector(".ptsp_users").clientHeight;
		//      console.log('ptsp_users_height->' + ptsp_users_height);
		that.to_say_height = banner_height + goods_info_height + hr_20_height + ptsp_users_height;
	} else {
		that.to_say_height = banner_height + goods_info_height + hr_20_height;
	}

	that.to_info_height = that.to_say_height + say_height + hr_20_height;
}
//初始化轮播
function slider_init() { //轮播 初始化
	var slider = mui("#slider");
	slider.slider({
		interval: 50000
	});
}
//轮播图片数量初始化
function init_banner_num() { //轮播图片数量初始化

	var count = document.querySelectorAll("#slider .mui-slider-item").length;

	document.querySelector(".ptsp_pic_i").innerHTML = '1';

	document.querySelector(".ptsp_pic_n").innerHTML = detail.wareInfoGroup.pics.length;

	document.querySelector('.mui-slider').addEventListener('slide', function(event) {

		document.querySelector(".ptsp_pic_i").innerHTML = event.detail.slideNumber + 1;
	});
}


function previewimage_init(){
 
	mui.previewImage();
}
